package com.deliverman.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * websocket 处理程序
 */
@Component
@Slf4j
public class MyWsHandler extends AbstractWebSocketHandler {

    static Map<String, SessionBean> sessions = new ConcurrentHashMap<String, SessionBean>();
    static AtomicInteger idMaker = new AtomicInteger(0);
    static StringBuffer stringBuffer = new StringBuffer();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        SessionBean sessionBean = new SessionBean(session, idMaker.getAndIncrement());
        sessions.put(session.getId(), sessionBean);

        log.info(sessions.get(session.getId()).getClientId()+"建立了连接");
        String msg = sessions.get(session.getId()).getClientId()+"加入了群聊<br/>";
        stringBuffer.append(msg);

        this.sendMsg();
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        log.info(sessions.get(session.getId()).getClientId()+": "+message.getPayload());
        String msg = sessions.get(session.getId()).getClientId()+"输入了"+message.getPayload()+"<br/>";
        stringBuffer.append(msg);
        this.sendMsg();
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        if (session.isOpen()){
            session.close();
        }
        sessions.remove(session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        Integer clientId = sessions.get(session.getId()).getClientId();
        sessions.remove(session.getId());
        log.info(clientId+"关闭了连接。 "+status.getCode()+", "+status.getReason());
        String msg = clientId +"退出了群聊<br/>";
        stringBuffer.append(msg);
        this.sendMsg();
    }

//    @Scheduled(fixedRate = 2000)
//    public void sendMsg() throws IOException {
//        log.info("sessions.size: "+sessions.size());
//        for(String key : sessions.keySet()) {
//            SessionBean session = sessions.get(key);
//
//            session.getWebSocketSession().sendMessage(new TextMessage("心跳了"));
//        }
//    }

    public void sendMsg() throws IOException {
        for(String key: sessions.keySet()){
            SessionBean sessionBean = sessions.get(key);
            sessionBean.getWebSocketSession().sendMessage(new TextMessage(stringBuffer.toString()));
        }
    }
}
